package com.appium.manager.element.anno;

import com.appium.manager.element.ElementHelper;
import com.appium.manager.element.anno.interceptor.PageInterceptor;
import com.appium.manager.template.AnnoAppiumHybridTemplate;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.WebElement;
import org.springframework.util.AntPathMatcher;

import java.util.*;


/**
 * <p>
 *     使用面向对象模式操作元素
 * </p>
 * @author 大忽悠
 * @create 2022/7/8 14:35
 */
public class PageElement extends ElementHelper {

    /**
     * 拦截器数组
     */
    private static Map<List<String>,PageInterceptor> interceptors=new LinkedHashMap<>();

    private static AntPathMatcher pathMatcher=new AntPathMatcher();


    private AnnoAppiumHybridTemplate annoAppiumHybridTemplate;


    public PageElement(AndroidDriver<WebElement> androidDriver,AnnoAppiumHybridTemplate appiumHybridTemplate) {
        super(androidDriver);
        this.annoAppiumHybridTemplate=appiumHybridTemplate;
    }

    public PageElement(AndroidDriver<WebElement> androidDriver,String testDataFilePath,AnnoAppiumHybridTemplate appiumHybridTemplate) {
        super(androidDriver,testDataFilePath);
        this.annoAppiumHybridTemplate=appiumHybridTemplate;
    }


    public void addInterceptor(PageInterceptor pageInterceptor, String ... methodNames){
        interceptors.put(Arrays.asList(methodNames),pageInterceptor);
    }

    public void invoke(String curTestMethodName) throws InterruptedException {
       if(curTestMethodName==null){
           throw new RuntimeException("请先设置当前正在执行的方法的名字");
       }
        List<PageInterceptor> interceptors = isMatch(curTestMethodName);
        for (PageInterceptor interceptor : interceptors) {
            interceptor.invoke(this,annoAppiumHybridTemplate);
        }
    }

    public List<PageInterceptor> isMatch(String methodName){
        List<PageInterceptor> res=new ArrayList<>();
        for (List<String> patterns : interceptors.keySet()) {
            for (String pattern : patterns) {
                if(pathMatcher.match(pattern,methodName)){
                    res.add(interceptors.get(patterns));
                    break;
                }
            }
        }
        return res;
    }

    public void initPage(Object page){
        annoAppiumHybridTemplate.initElements(page);
    }
}
